<template>
  <div class="">
    <!-- head -->
    <el-affix :offset="94">
      <div class="card affix-container pt15 pb14">
        <el-page-header @back="router.go(-1)">
          <template #content>
            <span class="fsize16">{{ isEdit ? "编辑特价折扣" : "新增特价折扣" }}</span>
          </template>
          <template #extra>
            <div class="foot">
              <el-button @click="router.go(-1)">取消</el-button>
              <el-button @click="onSubmit" type="primary">保存</el-button>
            </div>
          </template>
        </el-page-header>
      </div>
    </el-affix>
    <!-- head end -->
    <div class="card mt10">
      <el-form :model="couponForm" :disabled="couponForm.status !== 0" label-width="120px" :rules="couponRules" ref="ruleFormRef">
        <!-- 基础信息 -->
        <div class="group">
          <div class="section-title">基础信息</div>
          <el-form-item label="方案编码" prop="programmeCode">
            <el-input class="width320" v-model="couponForm.programmeCode" placeholder="请填写" :disabled="couponForm.id !== 0" />
          </el-form-item>
          <el-form-item label="方案名称" prop="programmeName">
            <el-input class="width320" v-model="couponForm.programmeName" placeholder="请填写" />
          </el-form-item>
          <el-form-item label="促销模式" prop="discountType">
            <el-select class="width320" v-model="couponForm.discountType" @change="handleDiscountType">
              <el-option v-for="mod in promotionMode" :key="mod.value" :label="mod.label" :value="mod.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="促销人群" prop="discountUserType">
            <el-select class="width320" v-model="couponForm.discountUserType">
              <el-option
                v-for="audience in promotionalAudience"
                :key="audience.value"
                :label="audience.label"
                :value="audience.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="有效期范围" prop="validityObject">
            <div>
              <el-date-picker
                class="width300"
                v-model="couponForm.validityObject"
                type="datetimerange"
                range-separator="至"
                :clearable="false"
                format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </div>
          </el-form-item>
          <el-form-item label="星期选择" prop="weekValueList">
            <div class="select-day-in-week-wrapper">
              <el-checkbox-group v-model="couponForm.weekValueList">
                <el-checkbox v-for="cycle in cycleData" :key="cycle.value" :label="cycle.value">{{ cycle.label }}</el-checkbox>
              </el-checkbox-group>
            </div>
          </el-form-item>
          <el-form-item label="菜品范围" prop="appointType">
            <el-radio-group v-model="couponForm.appointType" :disabled="couponForm.discountType !== 2">
              <el-radio :label="0">全部菜品</el-radio>
              <el-radio :label="1">指定菜品</el-radio>
              <el-radio :label="2">指定分类</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            v-if="!couponForm.appointType"
            label="全部菜品折扣"
            :rules="!couponForm.appointType ? [{ required: true, message: '请输入折扣' }] : []"
            prop="allDiscountValue"
          >
            <el-input class="width300" v-model="couponForm.allDiscountValue" placeholder="请输入菜品折扣"></el-input>
          </el-form-item>
          <el-form-item prop="foodCategoryList" v-if="couponForm.appointType === 2">
            <div>
              <el-button class="mb20" type="primary" v-if="couponForm.status === 0" @click="onFoodData">选择菜品分类</el-button>
              <div class="width500">
                <el-table size="small" :data="couponForm.foodCategoryList" border>
                  <el-table-column type="index" label="序号" width="60" />
                  <el-table-column prop="foodName" label="分类名称" />
                  <el-table-column prop="discountValue" label="促销折扣" width="120">
                    <template #default="scope">
                      <el-input-number class="w100" v-model="scope.row.discountValue" :min="1" :max="99" :controls="false" />
                    </template>
                  </el-table-column>
                  <el-table-column prop="address" label="操作" width="66">
                    <template #default="scope">
                      <el-button size="small" type="danger" @click="deleteSpecRow(scope.$index, 'type')">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </el-form-item>
          <el-form-item prop="foodList" v-if="couponForm.appointType === 1">
            <div>
              <el-button class="mb20" type="primary" v-if="couponForm.status === 0" @click="onFoodData">选择菜品</el-button>
              <el-table size="small" :data="couponForm.foodList" border>
                <el-table-column type="index" label="序号" width="60" align="center" />
                <el-table-column prop="foodName" label="商品名称" width="180" />
                <el-table-column prop="specName" label="型号规格" width="100" />
                <el-table-column
                  v-if="couponForm.discountType === 3 || couponForm.discountType === 4"
                  prop="posPrice"
                  label="原单价"
                  width="100"
                />
                <el-table-column v-if="couponForm.discountType === 2" prop="discountValue" label="促销折扣" width="100">
                  <template #default="scope">
                    <el-input-number class="w100" v-model="scope.row.discountValue" :min="1" :max="99" :controls="false" />
                  </template>
                </el-table-column>
                <el-table-column
                  v-if="couponForm.discountType === 2 || couponForm.discountType === 1"
                  label="零售单价（元）"
                  align="center"
                >
                  <el-table-column prop="posPrice" label="原单价" width="100" />
                  <el-table-column v-if="couponForm.discountType === 2" label="促销价" width="100">
                    <template #default="scope">
                      <el-text>{{ ((scope.row.discountValue / 100) * scope.row.posPrice).toFixed(2) }}</el-text>
                    </template>
                  </el-table-column>
                  <el-table-column v-if="couponForm.discountType === 1" label="特价" prop="discountPrice" width="100">
                    <template #default="scope">
                      <el-input-number class="w100" v-model="scope.row.discountPrice" :controls="false" />
                    </template>
                  </el-table-column>
                </el-table-column>
                <el-table-column label="菜品条码" prop="foodCode" width="100" />
                <el-table-column prop="address" label="操作" width="66">
                  <template #default="scope">
                    <el-button type="danger" size="small" @click="deleteSpecRow(scope.$index, 'food')">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-form-item>

          <el-form-item label="促销门店" prop="isAllUseStore">
            <el-radio-group v-model="couponForm.isAllUseStore">
              <el-radio :label="1">全部门店</el-radio>
              <el-radio :label="0">指定门店</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="storeList" v-if="couponForm.isAllUseStore !== 1">
            <div>
              <div class="mb20">
                <el-button type="primary" v-if="couponForm.status === 0" @click="openSelectTable('门店选择')">选择门店</el-button>
              </div>
              <el-table size="small" :data="couponForm.storeList" border>
                <el-table-column type="index" label="序号" width="60" />
                <el-table-column prop="useStoreId" label="门店编码" width="180" />
                <el-table-column prop="storeName" label="门店名称" width="120" />
                <el-table-column prop="address" label="操作" width="66">
                  <template #default="scope">
                    <el-button size="small" type="danger" @click="deleteSpecRow(scope.$index, 'store')">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <SelectTreeTable @selected-list="handleSelectedTreeList" ref="selectTreeTableRef" />
    <SelectTable @selected-list="handleSelectedList" ref="selectTableRef" />
  </div>
</template>
<script setup lang="ts" name="discountGoodsEdit">
import { ref, reactive, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { formatDate } from "@/utils/date-formatter";
import SelectTreeTable from "@/components/SelectTreeData/index.vue";
import SelectTable from "@/components/SelectTable/index.vue";
import { getFoodCategoryList, getGoodsList } from "@/api/modules/goods";
import { getStoreList } from "@/api/modules/operation";
import { createDiscountRules, editDiscountRules, getDiscountRules } from "@/api/modules/coupon";
import type { FormInstance } from "element-plus";
// import { promotionalAudience } from "@/utils/serviceDict";
import { replaceArrayItems } from "@/utils";
import { useSelectStore } from "@/stores/modules/dict";

const router = useRouter();
const route = useRoute();
const ruleFormRef = ref<FormInstance>();
const isEdit = ref(false);

interface CouponForm {
  id: number;
  programmeCode: string;
  programmeName: string;
  discountUserType: number;
  weekValueList: any[];
  validityObject: (one: number, two: string, three: string) => string[];
  appointType: number;
  discountType: number;
  isAllUseStore: number;
  foodList: any[];
  storeList: any[];
  status: number;
  foodCategoryList: any[];
  allDiscountValue: string;
}

const couponForm = reactive<CouponForm>({
  id: 0,
  programmeCode: "",
  programmeName: "",
  discountUserType: 0,
  weekValueList: [],
  validityObject: [formatDate(0, "start", "yyyy-MM-dd HH:mm"), formatDate(0, "end", "yyyy-MM-dd HH:mm")],
  appointType: 1,
  discountType: 1,
  allDiscountValue: "0",
  isAllUseStore: 1,
  foodList: [{ name: "" }],
  storeList: [],
  status: 0,
  foodCategoryList: []
});
const couponRules = reactive({
  programmeName: [{ required: true, message: "请填写方案名称" }],
  programmeCode: [{ required: true, message: "请填写方案编码" }],
  foodCategoryList: [{ required: true, message: "请选择菜品分类" }],
  foodList: [{ required: true, message: "请选择菜品" }],
  storeList: [{ required: true, message: "请选择门店" }]
});

const cycleData = reactive([
  { label: "星期一", value: 1 },
  { label: "星期二", value: 2 },
  { label: "星期三", value: 3 },
  { label: "星期四", value: 4 },
  { label: "星期五", value: 5 },
  { label: "星期六", value: 6 },
  { label: "星期日", value: 7 }
]);

const onFoodData = () => {
  if (couponForm.appointType === 1) {
    openSelectTreeTable("菜品选择");
  } else if (couponForm.appointType === 2) {
    openSelectTable("菜品分类选择");
  }
};

const selectTreeTableRef = ref<InstanceType<typeof SelectTreeTable> | null>(null);
const openSelectTreeTable = (title: string) => {
  console.log(couponForm.foodList);

  const params = {
    title,
    isView: false,
    index: 0,
    selTags: couponForm.foodList.map((i: any) => {
      i.name = i.foodName ? i.foodName : "";
      i.foodSpecId = i.foodOrCategoryId ? i.foodOrCategoryId : null;
      return i;
    }),
    // mate: "id",
    mate: "foodSpecId",
    columns: [
      { type: "selection", width: 62 },
      { prop: "name", label: "菜品名称", align: "left", minWidth: 200 },
      { prop: "foodTypeName", label: "分类" },
      { prop: "foodSpecName", label: "规格" },
      { prop: "posPrice", label: "菜品价格" }
    ],
    idName: "foodCategoryId",
    treeApi: getFoodCategoryList,
    api: getGoodsList
  };
  selectTreeTableRef.value?.acceptParams(params);
};

const handleSelectedTreeList = (val: any) => {
  if (val.list.length > 0) {
    let list = val.list.map((im: any) => {
      return {
        foodName: im.name,
        discountValue: 99,
        specName: im.foodSpecName,
        posPrice: im.posPrice,
        discountPrice: im.posPrice,
        foodOrCategoryId: im.foodSpecId,
        id: im.id
      };
    });
    couponForm.foodList = replaceArrayItems(list, couponForm.foodList, "foodOrCategoryId");
  } else {
    couponForm.foodList = [];
  }
};
const handleDiscountType = (val: number) => {
  if (val !== 2) {
    couponForm.appointType = 1;
  }
};
const selectTableRef = ref<InstanceType<typeof SelectTable> | null>(null);
const openSelectTable = (title: string) => {
  const params = {
    title,
    isView: false,
    selType: "selection",
    selTags:
      title === "菜品分类选择"
        ? couponForm.foodCategoryList.map(i => {
            return { name: i.foodName, id: i.foodOrCategoryId };
          })
        : couponForm.storeList.map(i => {
            return { name: i.storeName, id: i.useStoreId };
          }),
    columns:
      title === "菜品分类选择"
        ? [
            { type: "selection", width: 80 },
            { prop: "name", label: "分类名称", align: "left" }
          ]
        : [
            { type: "selection", width: 80 },
            { prop: "storeName", label: "门店名称", align: "left" }
          ],
    api: title === "菜品分类选择" ? getFoodCategoryList : getStoreList
  };
  selectTableRef.value?.acceptParams(params);
};
const handleSelectedList = (val: any) => {
  if (val.title === "菜品分类选择") {
    if (val.list.length > 0) {
      let list = val.list.map(im => {
        return {
          foodName: im.name,
          discountValue: 99,
          foodOrCategoryId: im.id
        };
      });
      couponForm.foodCategoryList = replaceArrayItems(list, couponForm.foodCategoryList, "foodOrCategoryId");
    } else {
      couponForm.foodCategoryList = [];
    }
  } else if (val.title === "门店选择") {
    if (val.list.length > 0) {
      couponForm.storeList = val.list.map(im => {
        return { useStoreId: im.id, storeName: im.name };
      });
    } else {
      couponForm.storeList = [];
    }
  }
};

const deleteSpecRow = (index: number, ty: string) => {
  if (ty === "type") {
    couponForm.foodCategoryList.splice(index, 1);
  } else if (ty === "food") {
    couponForm.foodList.splice(index, 1);
  } else if (ty === "store") {
    couponForm.storeList.splice(index, 1);
  }
};
const onSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      if (isEdit.value) {
        await editDiscountRules(couponForm).then(() => {
          router.push({
            path: "/marketing/discountGoods",
            query: {
              upList: true
            }
          });
        });
      } else {
        await createDiscountRules(couponForm).then(() => {
          router.push({
            path: "/marketing/discountGoods",
            query: {
              upList: true
            }
          });
        });
      }
    } catch (error) {
      console.log(error);
    }
  });
};
const promotionMode = ref([]);
const promotionalAudience = ref([]);
onMounted(async () => {
  try {
    const [discountTypes, discountUserTypes] = await Promise.all([
      useSelectStore().getDic("DiscountType"),
      useSelectStore().getDic("DiscountUserType")
    ]);

    promotionMode.value = discountTypes;
    promotionalAudience.value = discountUserTypes;

    if (route.query.id) {
      isEdit.value = true;
      const { data } = await getDiscountRules({ id: route.query.id });
      Object.keys(couponForm).forEach(key => {
        if (data.hasOwnProperty(key)) {
          couponForm[key] = data[key];
        }
      });
    }
  } catch (error) {
    // 错误处理逻辑
    console.error("An error occurred:", error);
  }
});
</script>

<style lang="scss" scoped>
.section-title {
  padding-left: 4px;
  margin-bottom: 26px;
  font-size: 14px;
  font-weight: 700;
  line-height: 14px;
  color: #333333;
  border-left: 4px solid var(--el-color-primary);
}
.select-day-in-week-wrapper {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 638px;
  padding: 12px 14px;
  font-family: PingFangSC-Regular;
  color: #222222;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}
</style>
